import { envConfig } from '@/config/env'
import { message } from 'ant-design-vue'

export interface WebSocketMessage {
  type: string
  data: any
  timestamp: number
}

export interface WebSocketOptions {
  url?: string
  protocols?: string | string[]
  reconnectInterval?: number
  maxReconnectAttempts?: number
  heartbeatInterval?: number
}

export class WebSocketManager {
  private ws: WebSocket | null = null
  private url: string
  private protocols?: string | string[]
  private reconnectInterval: number
  private maxReconnectAttempts: number
  private heartbeatInterval: number
  private reconnectAttempts = 0
  private heartbeatTimer: number | null = null
  private reconnectTimer: number | null = null
  private isConnecting = false
  private listeners: Map<string, Set<(data: any) => void>> = new Map()
  private subscriptions: Map<string, string> = new Map() // 存储订阅的主题

  constructor(options: WebSocketOptions = {}) {
    this.url = options.url || envConfig.wsBaseUrl
    this.protocols = options.protocols
    this.reconnectInterval = options.reconnectInterval || 5000
    this.maxReconnectAttempts = options.maxReconnectAttempts || 10
    this.heartbeatInterval = options.heartbeatInterval || 30000
  }

  // 连接WebSocket
  connect(): Promise<void> {
    return new Promise((resolve, reject) => {
      if (this.isConnecting || (this.ws && this.ws.readyState === WebSocket.CONNECTING)) {
        return
      }

      this.isConnecting = true

      try {
        this.ws = new WebSocket(this.url, this.protocols)

        this.ws.onopen = () => {
          console.log('WebSocket连接已建立')
          this.isConnecting = false
          this.reconnectAttempts = 0
          this.startHeartbeat()
          resolve()
        }

        this.ws.onmessage = (event) => {
          try {
            const message = JSON.parse(event.data)
            this.handleMessage(message)
          } catch (error) {
            console.error('解析WebSocket消息失败:', error)
          }
        }

        this.ws.onclose = (event) => {
          console.log('WebSocket连接已关闭:', event.code, event.reason)
          this.isConnecting = false
          this.stopHeartbeat()
          
          if (!event.wasClean && this.reconnectAttempts < this.maxReconnectAttempts) {
            this.scheduleReconnect()
          }
        }

        this.ws.onerror = (error) => {
          console.error('WebSocket连接错误:', error)
          this.isConnecting = false
          message.error('WebSocket连接失败')
          reject(error)
        }
      } catch (error) {
        this.isConnecting = false
        reject(error)
      }
    })
  }

  // 断开连接
  disconnect(): void {
    this.stopHeartbeat()
    this.stopReconnect()
    
    if (this.ws) {
      this.ws.close(1000, '主动断开连接')
      this.ws = null
    }
  }

  // 发送消息
  send(type: string, data: any): boolean {
    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      console.warn('WebSocket未连接，无法发送消息')
      return false
    }

    const message: WebSocketMessage = {
      type,
      data,
      timestamp: Date.now(),
    }

    try {
      this.ws.send(JSON.stringify(message))
      return true
    } catch (error) {
      console.error('发送WebSocket消息失败:', error)
      return false
    }
  }

  // 订阅消息
  subscribe(type: string, callback: (data: any) => void): () => void {
    if (!this.listeners.has(type)) {
      this.listeners.set(type, new Set())
    }
    
    this.listeners.get(type)!.add(callback)

    // 如果WebSocket已连接，立即订阅对应的主题
    if (this.isConnected) {
      this.subscribeToTopic(type)
    }

    // 返回取消订阅函数
    return () => {
      const callbacks = this.listeners.get(type)
      if (callbacks) {
        callbacks.delete(callback)
        if (callbacks.size === 0) {
          this.listeners.delete(type)
          this.unsubscribeFromTopic(type)
        }
      }
    }
  }

  // 订阅主题
  private subscribeToTopic(type: string): void {
    const topicMap: Record<string, string> = {
      'system_metrics': '/topic/monitoring/system',
      'life_entity_metrics': '/topic/monitoring/lifeentity',
      'activity_update': '/topic/monitoring/activity',
      'alert': '/topic/monitoring/alerts',
      'health_change': '/topic/monitoring/health',
      'ping': '/topic/pong'
    }

    const topic = topicMap[type]
    if (topic && !this.subscriptions.has(type)) {
      this.subscriptions.set(type, topic)
      // 这里简化处理，实际应该使用STOMP协议
      console.log(`订阅主题: ${topic}`)
    }
  }

  // 取消订阅主题
  private unsubscribeFromTopic(type: string): void {
    if (this.subscriptions.has(type)) {
      const topic = this.subscriptions.get(type)
      this.subscriptions.delete(type)
      console.log(`取消订阅主题: ${topic}`)
    }
  }

  // 处理接收到的消息
  private handleMessage(message: any): void {
    // 处理不同格式的消息
    let messageType: string
    let messageData: unknown

    if (message.type && message.data) {
      // 标准格式消息
      messageType = message.type
      messageData = message.data
    } else if (typeof message === 'object') {
      // 直接的对象消息
      messageType = message.type || 'unknown'
      messageData = message
    } else {
      console.warn('未知消息格式:', message)
      return
    }

    const callbacks = this.listeners.get(messageType)
    if (callbacks) {
      callbacks.forEach(callback => {
        try {
          callback(messageData)
        } catch (error) {
          console.error('处理WebSocket消息回调失败:', error)
        }
      })
    }
  }

  // 开始心跳
  private startHeartbeat(): void {
    this.stopHeartbeat()
    this.heartbeatTimer = window.setInterval(() => {
      this.send('ping', { timestamp: Date.now() })
    }, this.heartbeatInterval)
  }

  // 停止心跳
  private stopHeartbeat(): void {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer)
      this.heartbeatTimer = null
    }
  }

  // 计划重连
  private scheduleReconnect(): void {
    this.stopReconnect()
    this.reconnectAttempts++
    
    console.log(`计划第${this.reconnectAttempts}次重连...`)
    
    this.reconnectTimer = window.setTimeout(() => {
      this.connect().catch(() => {
        // 重连失败，继续尝试
      })
    }, this.reconnectInterval)
  }

  // 停止重连
  private stopReconnect(): void {
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer)
      this.reconnectTimer = null
    }
  }

  // 获取连接状态
  get readyState(): number {
    return this.ws?.readyState ?? WebSocket.CLOSED
  }

  // 是否已连接
  get isConnected(): boolean {
    return this.ws?.readyState === WebSocket.OPEN
  }
}

// 创建全局WebSocket实例
export const wsManager = new WebSocketManager()